/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Mantenimiento;


import Clases.CEntrada;
import Clases.CEntradaDetalle;
import Clases.CProducto;
import Clases.CProveedor;
import Modelo.Conection;
import Presentation.Main;
import java.awt.HeadlessException;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyVetoException;
import java.net.URL;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author Rudy
 */
public class Entradas extends javax.swing.JInternalFrame {

    /**
     * Creates new form Venta
     */
    Conection conection=new Conection();
    DefaultTableModel modelo,alter;
    Main main=new Main();
    public boolean edit=false;
    public int id_entrada=0;
  
    
    
    public Entradas() throws SQLException  {
        initComponents();
        conection.Conectar();
        AutoCompleteDecorator.decorate(jComboBoxEntradas);
        conection.cargarComboEntradas(jComboBoxEntradas);
        Inicializar();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btn_nuevo_proveedor = new javax.swing.JButton();
        dc_fecha = new com.toedter.calendar.JDateChooser();
        cbc_proveedor = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jLabelUsuario = new javax.swing.JLabel();
        jLabelDNI = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        cbp_producto = new javax.swing.JComboBox();
        btn_eliminar_producto = new javax.swing.JButton();
        btn_agregar_producto = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbl_entrada = new javax.swing.JTable();
        jLabel6 = new javax.swing.JLabel();
        tf_total = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        jButtonGuardar = new javax.swing.JButton();
        jButtonNuevo = new javax.swing.JButton();
        jButtonEliminar = new javax.swing.JButton();
        jComboBoxEntradas = new javax.swing.JComboBox();
        jToggleButtonBuscarEntradas = new javax.swing.JToggleButton();
        jCheckBoxCargarEntradas = new javax.swing.JCheckBox();

        setTitle("Entrada");
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                formMouseEntered(evt);
            }
        });
        addHierarchyListener(new java.awt.event.HierarchyListener() {
            public void hierarchyChanged(java.awt.event.HierarchyEvent evt) {
                formHierarchyChanged(evt);
            }
        });
        addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                formAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("DNI :");

        jLabel2.setText("Fecha :");

        btn_nuevo_proveedor.setText("Nuevo Proveedor");
        btn_nuevo_proveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_nuevo_proveedorActionPerformed(evt);
            }
        });

        cbc_proveedor.setEditable(true);

        jLabel9.setText("PROVEEDOR");

        jLabel4.setText("Nombre :");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbc_proveedor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelDNI, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabelUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 141, Short.MAX_VALUE)))
                .addGap(16, 16, 16)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btn_nuevo_proveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dc_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(2, 2, 2)))
                .addGap(63, 63, 63))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel2)
                        .addComponent(dc_fecha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabelUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabelDNI, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbc_proveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(btn_nuevo_proveedor))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel3.setText("Seleccione Producto :");

        cbp_producto.setEditable(true);
        cbp_producto.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                cbp_productoComponentHidden(evt);
            }
        });
        cbp_producto.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbp_productoItemStateChanged(evt);
            }
        });
        cbp_producto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbp_productoActionPerformed(evt);
            }
        });
        cbp_producto.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                cbp_productoFocusLost(evt);
            }
            public void focusGained(java.awt.event.FocusEvent evt) {
                cbp_productoFocusGained(evt);
            }
        });
        cbp_producto.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                cbp_productoInputMethodTextChanged(evt);
            }
        });
        cbp_producto.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                cbp_productoAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });
        cbp_producto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cbp_productoKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                cbp_productoKeyTyped(evt);
            }
        });

        btn_eliminar_producto.setText("Eliminar");
        btn_eliminar_producto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_eliminar_productoActionPerformed(evt);
            }
        });

        btn_agregar_producto.setText("Agregar");
        btn_agregar_producto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_agregar_productoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbp_producto, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(2, 2, 2)
                .addComponent(btn_agregar_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btn_eliminar_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbp_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_eliminar_producto)
                    .addComponent(jLabel3)
                    .addComponent(btn_agregar_producto))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                jPanel3MouseEntered(evt);
            }
        });
        jPanel3.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                jPanel3AncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        tbl_entrada.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod", "Producto", "Unidad Medida", "P.U", "Cantidad", "Sub Total", "Stock"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, true, true, true, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbl_entrada.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbl_entradaMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                tbl_entradaMouseEntered(evt);
            }
        });
        tbl_entrada.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbl_entradaKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(tbl_entrada);
        tbl_entrada.getColumnModel().getColumn(0).setMinWidth(90);
        tbl_entrada.getColumnModel().getColumn(0).setPreferredWidth(90);
        tbl_entrada.getColumnModel().getColumn(0).setMaxWidth(90);
        tbl_entrada.getColumnModel().getColumn(2).setPreferredWidth(5);
        tbl_entrada.getColumnModel().getColumn(3).setMinWidth(80);
        tbl_entrada.getColumnModel().getColumn(3).setPreferredWidth(80);
        tbl_entrada.getColumnModel().getColumn(3).setMaxWidth(80);
        tbl_entrada.getColumnModel().getColumn(4).setMinWidth(60);
        tbl_entrada.getColumnModel().getColumn(4).setPreferredWidth(60);
        tbl_entrada.getColumnModel().getColumn(4).setMaxWidth(60);
        tbl_entrada.getColumnModel().getColumn(5).setMinWidth(80);
        tbl_entrada.getColumnModel().getColumn(5).setPreferredWidth(80);
        tbl_entrada.getColumnModel().getColumn(5).setMaxWidth(80);
        tbl_entrada.getColumnModel().getColumn(6).setMinWidth(60);
        tbl_entrada.getColumnModel().getColumn(6).setPreferredWidth(60);
        tbl_entrada.getColumnModel().getColumn(6).setMaxWidth(60);

        jLabel6.setText("Total :");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(tf_total, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_total, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jButtonGuardar.setText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonNuevo.setText("Nuevo");
        jButtonNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNuevoActionPerformed(evt);
            }
        });

        jButtonEliminar.setText("Eliminar");
        jButtonEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEliminarActionPerformed(evt);
            }
        });

        jComboBoxEntradas.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBoxEntradasItemStateChanged(evt);
            }
        });

        jToggleButtonBuscarEntradas.setText("Buscar Entradas");
        jToggleButtonBuscarEntradas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jToggleButtonBuscarEntradasMouseClicked(evt);
            }
        });
        jToggleButtonBuscarEntradas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButtonBuscarEntradasActionPerformed(evt);
            }
        });

        jCheckBoxCargarEntradas.setText("Cargar Entrada");
        jCheckBoxCargarEntradas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jCheckBoxCargarEntradasMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addComponent(jButtonNuevo)
                .addGap(33, 33, 33)
                .addComponent(jButtonGuardar)
                .addGap(26, 26, 26)
                .addComponent(jButtonEliminar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jToggleButtonBuscarEntradas, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBoxEntradas, 0, 405, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCheckBoxCargarEntradas)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonGuardar)
                    .addComponent(jButtonNuevo)
                    .addComponent(jButtonEliminar)
                    .addComponent(jComboBoxEntradas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToggleButtonBuscarEntradas)
                    .addComponent(jCheckBoxCargarEntradas))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_nuevo_proveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_nuevo_proveedorActionPerformed
        // TODO add your handling code here:
        AddProveedor p= new AddProveedor(null, true);
        p.setVisible(true);
    }//GEN-LAST:event_btn_nuevo_proveedorActionPerformed

    private void btn_eliminar_productoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_eliminar_productoActionPerformed
        // TODO add your handling code here:    
        int f= tbl_entrada.getSelectedRow();
        //tf_total.setText(String.valueOf(Double.parseDouble(tf_total.getText())-Double.parseDouble(tbl_entrada.getValueAt(f, 5).toString())));
        if(edit==true){
            String id_producto = (String) modelo.getValueAt(f, 0);
            int cantidad = (int)modelo.getValueAt(f, 4);
            int stockActual =(int)modelo.getValueAt(f, 6);
            int stockNuevo=stockActual-cantidad;
            ArrayList columsProducto = new ArrayList();
            columsProducto.add("stock");
            ArrayList valuesProducto = new ArrayList();
            valuesProducto.add(stockNuevo);
            conection.update(columsProducto, valuesProducto, "tproducto", "id_producto='"+id_producto+"'");
        }
        modelo.removeRow(f);
        CalcularSubTotal();
    }//GEN-LAST:event_btn_eliminar_productoActionPerformed

    private void btn_agregar_productoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_agregar_productoActionPerformed
        AgregarProducto();
    }//GEN-LAST:event_btn_agregar_productoActionPerformed

    private void tbl_entradaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl_entradaKeyReleased
        // TODO add your handling code here:
        CalcularSubTotal();
    }//GEN-LAST:event_tbl_entradaKeyReleased

    private void tbl_entradaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_entradaMouseClicked
        // TODO add your handling code here:
        CalcularSubTotal();
    }//GEN-LAST:event_tbl_entradaMouseClicked

    private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
        try {
            guardarEntrada();
            this.setClosed(true);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(Entradas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButtonGuardarActionPerformed

    private void jButtonNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNuevoActionPerformed
        // TODO add your handling code here:
       Inicializar();
         
    }//GEN-LAST:event_jButtonNuevoActionPerformed

    private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarActionPerformed
        // TODO add your handling code here:
        if(id_entrada>0){
            conection.delete("tdetalle_entrada", "id_entrada="+id_entrada);
            conection.delete("tentrada", "id_entrada="+id_entrada);
            //actualizar el stock de los productos
            int filas = modelo.getRowCount();
            for (int i = 0; i < filas; i++) {
                String id_producto = (String) modelo.getValueAt(i, 0);
                int cantidad = Integer.valueOf(modelo.getValueAt(i, 4).toString());
                int stockActual =(int)modelo.getValueAt(i, 6);
                int nuevoStock = stockActual-cantidad;
                ArrayList columsProducto = new ArrayList();
                columsProducto.add("stock");
                ArrayList valuesProducto = new ArrayList();
                valuesProducto.add(nuevoStock);
                conection.update(columsProducto, valuesProducto, "tproducto", "id_producto='"+id_producto+"'");
            }
        }
    }//GEN-LAST:event_jButtonEliminarActionPerformed

    private void jToggleButtonBuscarEntradasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jToggleButtonBuscarEntradasMouseClicked
        // TODO add your handling code here:
        if (jToggleButtonBuscarEntradas.isSelected()) {
            // TODO add your handling code here:
            jToggleButtonBuscarEntradas.setText("No Buscar Entrada");
            jComboBoxEntradas.setVisible(true);
            jButtonEliminar.setVisible(true);
            jCheckBoxCargarEntradas.setVisible(true);
        }else{
            jToggleButtonBuscarEntradas.setText("Buscar Entrada");
            jComboBoxEntradas.setVisible(false);
            jButtonEliminar.setVisible(false);
            jCheckBoxCargarEntradas.setVisible(false);
            Inicializar();

            
        }
    }//GEN-LAST:event_jToggleButtonBuscarEntradasMouseClicked

    private void jCheckBoxCargarEntradasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jCheckBoxCargarEntradasMouseClicked
        // TODO add your handling code here:
        if (jCheckBoxCargarEntradas.isSelected()) {
            BuscarEntrada();
            edit=true;
        }
    }//GEN-LAST:event_jCheckBoxCargarEntradasMouseClicked

    private void jComboBoxEntradasItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxEntradasItemStateChanged
        // TODO add your handling code here:
        jCheckBoxCargarEntradas.setSelected(false);
    }//GEN-LAST:event_jComboBoxEntradasItemStateChanged

    private void formHierarchyChanged(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_formHierarchyChanged
        // TODO add your handling code here:
        
    }//GEN-LAST:event_formHierarchyChanged

    private void cbp_productoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cbp_productoFocusGained
        // TODO add your handling code here:
        
    }//GEN-LAST:event_cbp_productoFocusGained

    private void cbp_productoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cbp_productoFocusLost
        // TODO add your handling code here:
        
    }//GEN-LAST:event_cbp_productoFocusLost

    private void cbp_productoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbp_productoActionPerformed
        // TODO add your handling code her
        
    }//GEN-LAST:event_cbp_productoActionPerformed

    private void cbp_productoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbp_productoItemStateChanged
        // TODO add your handling code here:
        
    }//GEN-LAST:event_cbp_productoItemStateChanged

    private void formAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_formAncestorAdded
        // TODO add your handling code here:
        cbp_producto.nextFocus();
    }//GEN-LAST:event_formAncestorAdded

    private void jToggleButtonBuscarEntradasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButtonBuscarEntradasActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jToggleButtonBuscarEntradasActionPerformed

    private void cbp_productoAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_cbp_productoAncestorAdded
        // TODO add your handling code here:
        
    }//GEN-LAST:event_cbp_productoAncestorAdded

    private void cbp_productoInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_cbp_productoInputMethodTextChanged
        // TODO add your handling code here:
        
    }//GEN-LAST:event_cbp_productoInputMethodTextChanged

    private void jPanel3AncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_jPanel3AncestorAdded
        // TODO add your handling code here:
        
    }//GEN-LAST:event_jPanel3AncestorAdded

    private void jPanel3MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel3MouseEntered
        // TODO add your handling code here:
        
    }//GEN-LAST:event_jPanel3MouseEntered

    private void tbl_entradaMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_entradaMouseEntered
        // TODO add your handling code here:
        
    }//GEN-LAST:event_tbl_entradaMouseEntered

    private void cbp_productoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cbp_productoKeyPressed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_cbp_productoKeyPressed

    private void formMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseEntered
        // TODO add your handling code here:
        
    }//GEN-LAST:event_formMouseEntered

    private void cbp_productoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cbp_productoKeyTyped
        // TODO add your handling code here:
        
    }//GEN-LAST:event_cbp_productoKeyTyped

    private void cbp_productoComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_cbp_productoComponentHidden
        // TODO add your handling code here:
        AgregarProducto();
    }//GEN-LAST:event_cbp_productoComponentHidden

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_agregar_producto;
    private javax.swing.JButton btn_eliminar_producto;
    private javax.swing.JButton btn_nuevo_proveedor;
    public static javax.swing.JComboBox cbc_proveedor;
    public static javax.swing.JComboBox cbp_producto;
    private com.toedter.calendar.JDateChooser dc_fecha;
    private javax.swing.JButton jButtonEliminar;
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonNuevo;
    private javax.swing.JCheckBox jCheckBoxCargarEntradas;
    private javax.swing.JComboBox jComboBoxEntradas;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabelDNI;
    private javax.swing.JLabel jLabelUsuario;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToggleButton jToggleButtonBuscarEntradas;
    public static javax.swing.JTable tbl_entrada;
    private javax.swing.JTextField tf_total;
    // End of variables declaration//GEN-END:variables
    

    public void CalcularSubTotal() throws NumberFormatException {
        // TODO add your handling code here:
        modelo = (DefaultTableModel)tbl_entrada.getModel();
        int fila = modelo.getRowCount();
        //int col = modelo.getColumnCount();
        float suma=0;
        for (int i = 0; i < fila; i++) {
            if(modelo.getValueAt(i, 3) != null){
                if(!modelo.getValueAt(i, 4).toString().equals(""))
                {
                    modelo.setValueAt(((Float.parseFloat(modelo.getValueAt(i, 3).toString()))*(Float.parseFloat(modelo.getValueAt(i, 4).toString()))), i, 5);
                }                
                suma += (Float.parseFloat(modelo.getValueAt(i, 5).toString()));
            }
        }
        tf_total.setText(String.valueOf(suma));
    }
    public void ActualizarStock() throws HeadlessException, NumberFormatException {
        // TODO add your handling code here:
        int fila=1;
        try {
             fila= tbl_entrada.getRowCount();
        } catch (Exception e) {
        }
        for (int i = 0; i < fila; i++) {
            int cant =Integer.parseInt(tbl_entrada.getValueAt(i, 4).toString());
            int st =Integer.parseInt(tbl_entrada.getValueAt(i, 6).toString());
            
            tbl_entrada.setValueAt(st+cant, i, 6);
        }
    }

    private void guardarEntrada() throws NumberFormatException {
        // TODO add your handling code here:
        String fecha = new SimpleDateFormat("yyyy-MM-dd").format(dc_fecha.getDate());
        String dni = Main.dni;
        CProveedor P = (CProveedor)cbc_proveedor.getSelectedItem();
        String ruc = P.getRuc();
        ArrayList columnasEntrada = new ArrayList();
        columnasEntrada.add("fecha");
        columnasEntrada.add("dni");
        columnasEntrada.add("ruc");
        ArrayList valoresEntrada = new ArrayList();
        valoresEntrada.add(fecha);
        valoresEntrada.add(dni);
        valoresEntrada.add(ruc);
        //----faltaaa
        if(edit==false){
            conection.insert(columnasEntrada, valoresEntrada, "tentrada");
            id_entrada = conection.getUltimoId("id_entrada", "tentrada");
        }else{
            conection.update(columnasEntrada, valoresEntrada, "tentrada", "id_entrada="+id_entrada);
            conection.delete("tdetalle_entrada", "id_entrada="+id_entrada);
        }
        int filas = modelo.getRowCount();
        for (int i = 0; i < filas; i++) {
            int cantidad = Integer.valueOf(modelo.getValueAt(i, 4).toString());
            String id_producto = (String) modelo.getValueAt(i, 0);
            double precio_compra = Double.parseDouble(modelo.getValueAt(i, 3).toString());
            String unidad_medida= (String)modelo.getValueAt(i, 2);
            ArrayList columnasEntradaDetalle = new ArrayList();
            columnasEntradaDetalle.add("cantidad");
            columnasEntradaDetalle.add("id_entrada");
            columnasEntradaDetalle.add("id_producto");
            columnasEntradaDetalle.add("precio_compra");
            columnasEntradaDetalle.add("unidad_medida");
            ArrayList valoresEntradaDetalle = new ArrayList();
            valoresEntradaDetalle.add(cantidad);
            valoresEntradaDetalle.add(id_entrada);
            valoresEntradaDetalle.add(id_producto);
            valoresEntradaDetalle.add(precio_compra);
            valoresEntradaDetalle.add(unidad_medida);
            conection.insert(columnasEntradaDetalle, valoresEntradaDetalle, "tdetalle_entrada");
            //actualizar stock del producto
            int stockActual =(int)modelo.getValueAt(i, 6);
            int nuevoStock = stockActual+cantidad;
            ArrayList columsProducto = new ArrayList();
            columsProducto.add("stock");
            ArrayList valuesProducto = new ArrayList();
            valuesProducto.add(nuevoStock);
            conection.update(columsProducto, valuesProducto, "tproducto", "id_producto='"+id_producto+"'");
        }
        JOptionPane.showMessageDialog(this, "Entrada registrada correctamente ...","Informacion",JOptionPane.INFORMATION_MESSAGE);
    }

    private void BuscarEntrada() {
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:

            
            CEntrada E = (CEntrada)jComboBoxEntradas.getSelectedItem();
                 //entrada
                 jLabelDNI.setText(E.getDni());
                 ResultSet rs =conection.Seleccion("tusuario","dni="+E.getDni());
                 //jLabelUsuario.setText(rs.getString("usuario").toString());
                 if(rs.next()){
                     jLabelUsuario.setText(rs.getString("usuario").toString());
                 }
                 ResultSet rsP =conection.Seleccion("tproveedor","ruc="+E.getRuc());
                 if (rsP.next()) {
                    CProveedor pro = new CProveedor();
                    pro.setRuc(rsP.getString("ruc"));
                    pro.setRazonSocial(rsP.getString("razon_social"));
                    pro.setDireccion(rsP.getString("direccion"));
                    pro.setEmail(rsP.getString("email"));
                    pro.setTelefono(rsP.getString("telefono"));
                    pro.setWeb(rsP.getString("web"));
                    cbc_proveedor.setSelectedItem(pro);
                }
                dc_fecha.setDate(E.getFecha());
                //detalle entrada
                ResultSet rsED =conection.Seleccion("tdetalle_entrada","id_entrada="+E.getIdEntrada());
                ArrayList filas = new ArrayList();
                while(rsED.next()){
                    CEntradaDetalle ED = new CEntradaDetalle();
                    ED.setIdDetalle(rsED.getInt("id_detalle"));
                    ED.setCantidad(rsED.getInt("cantidad"));
                    ED.setIdEntrada(rsED.getInt("id_entrada"));
                    ED.setIdProducto(rsED.getString("id_producto"));
                    ED.setPrecioUnitario(rsED.getFloat("precio_compra"));
                    ED.setUnidadMedida(rsED.getString("unidad_medida"));
                    filas.add(ED);
                }
                modelo = (DefaultTableModel)tbl_entrada.getModel();
                for (int i = 0; i < filas.size(); i++) {
                        CEntradaDetalle ED =(CEntradaDetalle)filas.get(i);
                        String dato =ED.getIdProducto();
                        modelo.setRowCount(filas.size());
                        modelo.setValueAt(ED.getIdProducto(), i, 0);
                        ResultSet p =conection.Seleccion("tproducto","id_producto='"+ED.getIdProducto()+"'");
                        if (p.next()) {
                            modelo.setValueAt(p.getString("nombre"), i, 1);
                        }
                        modelo.setValueAt(ED.getUnidadMedida(), i, 2);
                        modelo.setValueAt(ED.getPrecioUnitario(), i, 3);
                        modelo.setValueAt(ED.getCantidad(), i, 4);
                        modelo.setValueAt(p.getInt("stock"), i, 6);
                }
                CalcularSubTotal();
                id_entrada=E.getIdEntrada();
        } catch (SQLException ex) {
            Logger.getLogger(Entradas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void Inicializar() {
        try {
            if(Main.tipe==1){
                jToggleButtonBuscarEntradas.setVisible(true);
            }else{
                jToggleButtonBuscarEntradas.setVisible(false);
            }
            jLabelDNI.setText("");
            jLabelUsuario.setText("");
            conection.cargarComboProducto(cbp_producto);        
            AutoCompleteDecorator.decorate(cbp_producto);
            conection.cargarComboProveedor(cbc_proveedor);        
            AutoCompleteDecorator.decorate(cbc_proveedor);
            jComboBoxEntradas.setVisible(false);
            jButtonEliminar.setVisible(false);
            jCheckBoxCargarEntradas.setVisible(false);
            Date date = new Date();
            dc_fecha.setDate(date);
            edit =false;
            //este codigo limpia la tabla o inicializa la tabla nuevamente cuannod el grover quiere
            try {
	            DefaultTableModel modelo=(DefaultTableModel) tbl_entrada.getModel();
            int filas=tbl_entrada.getRowCount();
            for (int i = 0;filas>i; i++) {
	                modelo.removeRow(0);
	            }
	        } catch (Exception e) {
	            JOptionPane.showMessageDialog(null, "Error al limpiar la tabla.");
	        }
           tf_total.setText("");
        } catch (SQLException ex) {
            Logger.getLogger(Entradas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void AgregarProducto() throws NumberFormatException, HeadlessException {
        // TODO add your handling code here:
        
        if(conection.Existe(cbp_producto.getSelectedItem().toString(), "id_producto", "tproducto")){
        CProducto P = (CProducto)cbp_producto.getSelectedItem();
        modelo = (DefaultTableModel)tbl_entrada.getModel();
        boolean si=false;
        for (int i = 0; i < modelo.getRowCount(); i++) {
            if(!modelo.getValueAt(i, 0).toString().equals(""))
            {
                if(P.getIdProducto()==modelo.getValueAt(i, 0).toString())
                {
                    si=true;
                    JOptionPane.showMessageDialog(Entradas.this,"Producto en lista \nSolo edite la cantidad en la tabla.", "ATENCION", JOptionPane.INFORMATION_MESSAGE);
                    i=modelo.getRowCount();
                }
            }
        }
        if(si==false)
        {
            Object D[] ={P.getIdProducto(),P.getNombre()};
            modelo.addRow(D);
            int fila = tbl_entrada.getRowCount();
            modelo.setValueAt(P.getPrecio_unitario(), fila-1, 3);
            modelo.setValueAt(1, fila-1, 4);
            modelo.setValueAt(P.getStock(), fila-1, 6);
        }
        CalcularSubTotal();
    }else{
            JOptionPane.showMessageDialog(this, "Producto no registrado ...", "Informacion", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

